<?php

use liketp\facade\Event;
use liketp\Response;
use liketp\Log;

if (file_exists('is_cli') == false) {
    function is_cli()
    {
        return in_array(php_sapi_name(), ['cli']);
    }
}

if (function_exists('dump') == false) {
    function dump()
    {
        $args = func_get_args();
        foreach ($args as $v) {
            if (is_array($v) || is_object($v)) {
                echo is_cli() ? PHP_EOL : '<pre>';
                print_r($v);
                echo is_cli() ? PHP_EOL : '</pre>';
            } else {
                var_dump($v);
            }
            echo is_cli() ? PHP_EOL : '<br>';
            echo '----------------------------';
            echo is_cli() ? PHP_EOL : '<br>';
        }
    }
}

if (function_exists('dp') == false) {
    function dp()
    {
        $args = func_get_args();
        foreach ($args as $v) {
            if (is_array($v) || is_object($v)) {
                echo is_cli() ? PHP_EOL : '<pre>';
                print_r($v);
                echo is_cli() ? PHP_EOL : '</pre>';
            } else {
                var_dump($v);
            }
            echo is_cli() ? PHP_EOL : '<br>';
            echo '----------------------------';
            echo is_cli() ? PHP_EOL : '<br>';
        }
    }
}

if (function_exists('halt') == false) {
    function halt()
    {
        $args = func_get_args();
        call_user_func_array('dump', $args);
        die;
    }
}

if (function_exists('parse_env') == false) {
    function parse_env(array $lineArr)
    {
        $res = [];
        $prefix = '';
        foreach ($lineArr as $line) {
            $line = trim($line);
            if (substr($line, 0, 1) == '#') continue;

            preg_match('/\[(\w+)\]/', $line, $match);
            if (isset($match[1])) {
                $prefix = trim($match[1]);
                continue;
            }

            if (strpos($line, '=') > 0) {
                [$key, $val] = explode('=', $line, 2);
                $key = strtolower(trim($key));
                $val = trim($val);

                $val = trans_str_val($val, true);

                if ($prefix == '') {
                    $res[$key] = $val;
                    continue;
                }

                if (isset($res[$prefix]) && is_array($res[$prefix])) {
                    $res[$prefix][$key] = $val;
                } else {
                    $res[$prefix] = [$key => $val];
                }
            }
        }
        return $res;
    }
}

if (function_exists('env') == false) {
    function env(?string $key = null, $default = '')
    {
        return app()->env($key, $default);
    }
}

if (function_exists('trans_str_val') == false) {
    function trans_str_val(string $str, $transNum = false)
    {
        if (strtolower($str) == 'false') return false;
        if (strtolower($str) == 'true')  return true;
        if (strtolower($str) == 'null')  return null;

        //specify string
        if (preg_match('/^([\'"])(.*)\1$/', $str, $match)) {
            return $match[2];
        }

        //number
        if ($transNum && is_numeric($str)) return $str * 1;

        //array
        if (preg_match('/^\[(.*)\]$/', $str, $match)) {
            $arr = explode(',', $match[1]);
            array_walk($arr, function (&$val) use ($transNum) {
                $val = trans_str_val(trim($val), $transNum);
            });
            return $arr;
        }

        return $str;
    }
}

if (function_exists('app') == false) {
    function app(string $abstract = '', array $arguments = [], bool $newInstance = false)
    {
        $app = \liketp\App::instance();
        return $abstract ? $app->make($abstract, $arguments, $newInstance) : $app;
    }
}

if (function_exists('config') == false) {
    function config(?string $key = null, $default = null)
    {
        return app('config')->config($key, $default);
    }
}

if (function_exists('config_get') == false) {
    function config_get(array $data, string $key, $default = null)
    {
        return app('config')->get($key, $default, $data);
    }
}

if (function_exists('not_in_array') == false) {
    function not_in_array($val, $array, bool $strict = false)
    {
        return in_array($val, $array, $strict) == false;
    }
}

if (function_exists('array_cast') == false) {
    function array_cast($mainArr, $valueArr)
    {
        foreach ($mainArr as $k => $v) {
            if (isset($valueArr[$k])) {
                $mainArr[$k] = $valueArr[$k];
            }
        }
        return $mainArr;
    }
}

if (function_exists('request') == false) {
    function request()
    {
        return app('request');
    }
}

if (function_exists('to_str') == false) {
    function to_str($data)
    {
        if (is_array($data)) {
            return json_encode($data);
        } else if (is_object($data)) {
            if (method_exists($data, '__toString')) {
                return (string)$data;
            }
        } else if (is_scalar($data)) {
            return (string) $data;
        }
        return '';
    }
}

if (function_exists('str_to_camel') == false) {
    function str_to_camel(string $str, bool $ucFirst = false): string
    {
        $str = preg_replace('/[-_]+/', ' ', $str);
        $str = preg_replace('/\s+/', '', ucwords($str));

        return $ucFirst ? $str : lcfirst($str);
    }
}

if (function_exists('str_to_snake') == false) {
    function str_to_snake(string $str, string $delimiter = '_')
    {
        $str = preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $str);
        return strtolower($str);
    }
}

if (function_exists('input') == false) {
    function input($name = null, $default = null, $filter = '')
    {
        return app('request')->param($name, $default, $filter);
    }
}

if (function_exists('response') == false) {
    function response($data = '', int $code = 200, array $header = [], string $type = 'html'): Response
    {
        return Response::create($data, $type, $code)->header($header);
    }
}

if (function_exists('html') == false) {
    function html($data, int $code = 200, array $header = [])
    {
        return Response::create($data, 'html', $code)->header($header);
    }
}

if (function_exists('view') == false) {
    function view(?string $tpl = null, ?array $data = null, bool $isTplContent = false, int $code = 200): Response
    {
        return Response::create($data, 'view', $code)->tpl($tpl)->isTplContent($isTplContent);
    }
}

if (function_exists('json') == false) {
    function json($data, int $code = 200, array $header = [], array $options = [])
    {
        return Response::create($data, 'json', $code)->header($header)->options($options);
    }
}

if (function_exists('jsonp') == false) {
    function jsonp($data, int $code = 200)
    {
        return Response::create($data, 'jsonp', $code);
    }
}

if (function_exists('xml') == false) {
    function xml($data, int $code = 200)
    {
        return Response::create($data, 'xml', $code);
    }
}

if (function_exists('redirect') == false) {
    function redirect($url, int $code = 302)
    {
        return Response::create($url, 'redirect', $code);
    }
}

if (function_exists('download') == false) {
    function download($src, $name = '')
    {
        return Response::create($src, 'file', 200)->name($name);
    }
}

if (function_exists('trace') == false) {
    function trace($msg, $type)
    {
        Log::record($msg, $type);
    }
}

if (function_exists('event') == false) {
    function event($eventFlag, $argument = null)
    {
        return Event::trigger($eventFlag, $argument);
    }
}
